import csv
import os
from inventory.models import Item,Location

def check_cas(cas_num):
	cas = cas_num[::-1].replace('-','')[1::]
	check = cas_num[-1]
	
	total = 0
	for idx,val in enumerate(cas):
		total += int(val)*(idx+1)
		
	return (total % 10) == int(check)

def check_all(filename):
	print "checking %s" % filename
	checks = []
	idx = 0
	for row in csv.reader(open(filename,'rU')):
		idx += 1
		if not row[1].replace('-','').isdigit():
			checks.append([idx, "non number"])
		elif not check_cas(row[1]):
			checks.append([idx, row[1]])
	return checks

def check_dir(directory):
	checks = []
	for root,dirs,files in os.walk(directory,topdown=False):
		for name in files:
			if name[0] == '.':
				continue
			checks.append([name, check_all(os.path.join(root,name))])
	return checks
	
def print_check(dir):
	a = check_dir(dir)
	for sheet in a:
		if len(sheet[1]) == 0:
			continue
		print "Filename: %s" % sheet[0]
		for error in sheet[1]:
			print "\t%s" % error
		print "-----------------"
		
def csv_files(directory):
	files = []
	def ext(name):
		return os.path.splitext(name)[1]
	for root,dirs,files in os.walk(directory, topdown=False):
		for name in files:
			if name[0] == '.':
				continue
			if ext(name) != 'csv':
				pass
			yield os.path.join(root,name)
			
def import_all():
	files = csv_files('csvs')
	locations = Location.objects.all()
	loc_map = dict()
	for loc in locations:
		loc_map[loc.coded_name] = loc
		
	printed = False
	for f in files:
		printed = False
		for row in csv.reader(open(f,'rU')):
			chem_name = row[0]
			chem_cas = row[1]
			chem_formula = row[2]
			chem_quantity = row[3]
			chem_manuf = row[4]
			chem_location = row[5]
			if chem_location not in loc_map:
				print "%s: %s not found" % (f, location,)
			chem_comment = row[6]
			if len(row) > 7:
				chem_class = row[7]
			else:
				chem_class = ''
			if len(row) > 8:
				print "ERROR, row len greater than 8"
				print row
				break
			i = Item(
				name = chem_name,
				location=loc_map[chem_location],
				cas_num = chem_cas,
				quantity = chem_quantity,
				classification = chem_class,
				supplier = chem_manuf,
				mol_formula = chem_formula,
				properties = chem_comment)
			i.save()
